// 导入模块
const fs = require('fs')
const path = require('path')

function getFullPath(fileName) {
    const fullPath = path.join(__dirname, `./data/${fileName}`)
    return fullPath
}

function news() {
    // 1. 获取绝对路径
    const fullPath = getFullPath('news.json')
    // 2. 读取
    const res = fs.readFileSync(fullPath, 'utf-8')
    // console.log(res)
    // 3. 转换为对象
    const news = JSON.parse(res)
    // console.log(news)
    // 4. 返回
    return news
}
function students() {
    // 1. 获取绝对路径
    const fullPath = getFullPath('info.json')
    // 2. 读取
    const res = fs.readFileSync(fullPath, 'utf-8')
    // console.log(res)
    // 3. 转换为对象
    const students = JSON.parse(res)
    // console.log(students)
    // 4. 返回
    return students
}
function luckystar() {

    const fullPath = getFullPath('info.json')
    const studentArr = students()
    // 3. 随机取一个下标
    const index = parseInt(Math.random() * studentArr.length)
    const luckystar = studentArr[index]
    luckystar.count++
    fs.writeFileSync(fullPath, JSON.stringify(studentArr))
    return luckystar
}
module.exports = {
    news,
    students,
    luckystar
}